﻿using System.IO;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Bundle
{
    public string url;
    public string bundlekey;
    public int version;
}

public class BundleManager : MonoBehaviour
{
    List<Bundle> bundlesToDownload;
    public static Dictionary<string, AssetBundle> bundleList;
    private WWW www;
    private int currentBundle;
    private bool isBeginRequest = false;
    private float elapsedTime = 0f;
    private float waitTime = 5f;
    public UILabel lbTip;
    public UILabel dot;
    delegate void Callback();
    private static Callback openBundleSuccessCallback;
    public delegate void AssetCallback(UnityEngine.Object toLoadObject);

    void Awake()
    {
        DontDestroyOnLoad(this);
        bundlesToDownload = new List<Bundle>();
        bundleList = new Dictionary<string, AssetBundle>();
    }

    void Start()
    {

        

    }

  

  

   
    
    

    

    

    public static UnityEngine.Object LoadPrefab(string prefabName, string editorPath = "")
    {
        return Load<UnityEngine.Object>(prefabName, editorPath, ".prefab");
    }

    public static AudioClip LoadAudioClip(string audioName, string ext = ".ogg", string editorPath = "sounds")
    {
        return Load<AudioClip>(audioName, editorPath, ext);
    }

    public static AudioClip LoadAudioClipMP3(string audioName, string ext = ".mp3", string editorPath = "sounds")
    {
        return Load<AudioClip>(audioName, editorPath, ext);
    }


    public static IEnumerator LoadPrefabAsync(string prefabName, string editorPath, AssetCallback assetCallback)
    {
#if UNITY_EDITOR

        yield return null;

        if ("".Equals(editorPath))
        {
            editorPath = "Assets/AssetBundles/Prefab/";
        }
        else
        {
            editorPath = "Assets/AssetBundles/Prefab/" + editorPath + "/";
        }

        assetCallback(UnityEditor.AssetDatabase.LoadAssetAtPath(editorPath + prefabName + ".prefab", typeof(GameObject)));

#else

                string[] bundleKeys = editorPath.Split ('/');
                string bundleKey = "Prefabs_" + bundleKeys [0];
		
                if ("".Equals (editorPath)) {
                        editorPath = "Prefab/";
                } else {
                        editorPath = "Prefab/" + editorPath + "/";
                }

                ResourceRequest resourceRequest = Resources.LoadAsync (editorPath + prefabName);
                yield return resourceRequest;
                UnityEngine.Object prefabObject = resourceRequest.asset;
                if (prefabObject != null)
                        assetCallback (prefabObject);
                else {
                        AssetBundle bundle = bundleList [bundleKey];
		
                        if (bundle == null) {
                                Debuger.Log ("asset bundle is null");
                                yield return null;
                        }

                        AssetBundleRequest request = bundle.LoadAssetAsync (prefabName, typeof(GameObject));
                        yield return request;
                        prefabObject = request.asset;
                        assetCallback (prefabObject);
                }
				
#endif
    }

    /// <summary>
    /// 优先在Resource文件夹下寻找然后在AB中寻找
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="prefabName">文件名字</param>
    /// <param name="editorPath">Resource子文件夹或者bundleList的KEY</param>
    /// <param name="fileExt">后缀</param>
    /// <returns></returns>
    public static T Load<T>(string prefabName, string editorPath, string fileExt) where T : class
    {

        
        #if UNITY_EDITOR
        if ("".Equals(editorPath))
        {
            editorPath = "Assets/Resources/";
        }
        else
        {
            editorPath = "Assets/Resources/" + editorPath + "/";
        }

        //if ("".Equals(editorPath))
        //{
        //    editorPath = "Assets/AssetBundles/";
        //}
        //else
        //{
        //    editorPath = "Assets/AssetBundles/" + editorPath + "/";
        //}



        return UnityEditor.AssetDatabase.LoadAssetAtPath(editorPath + prefabName + fileExt, typeof(T)) as T;


//#if UNITY_EDITOR //测试！EDITOR测试的时候直接把预制放到这直接读取
        

//        
#else  //正式！其他平台从BUNDLE里面读

        string[] bundleKeys = editorPath.Split('/');
        string bundleKey = bundleKeys[0];

        if ("".Equals(editorPath))
        {
            editorPath = "";
        }
        else
        {
            editorPath = editorPath + "/";
        }
        Debuger.Log("editorPath:" + editorPath + "::" + prefabName);
        T prefabObject = Resources.Load(editorPath + prefabName) as T;
        if (prefabObject != null)
            return prefabObject;

        AssetBundle bundle; 
        if(bundleList == null)return null;
        if(!bundleList.TryGetValue(bundleKey,out bundle))
            return null;
        prefabObject = bundle.LoadAsset(prefabName) as T;
        return prefabObject;

#endif
    }

    public static T[] LoadAll<T>(string editorPath = "") where T : class
    {
#if UNITY_EDITOR
        var path = "";
        if ("".Equals(editorPath))
        {
            path = Path.Combine(Application.dataPath, "AssetBundles");
        }
        else
        {
            path = Path.Combine(Path.Combine(Application.dataPath, "AssetBundles"), editorPath);
        }
        List<T> result = new List<T>();
        var dir = new DirectoryInfo(path);
        foreach (var item in dir.GetFiles())
        {
            if (item.Extension != ".meta")
            {
                var tmp = Load<T>(item.Name.Remove(item.Name.LastIndexOf('.')), editorPath, item.Extension);
                result.Add(tmp);
            }
        }
        return result.ToArray();

#else
        string[] bundleKeys = editorPath.Split('/');
        string bundleKey = bundleKeys[0];

        if ("".Equals(editorPath))
        {
            editorPath = "";
        }
        else
        {
            editorPath = editorPath + "/";
        }
        var objs = Resources.LoadAll(editorPath);

        T[] prefabObject = null;
        if (objs != null && objs.Length > 0)
        {
            prefabObject = new T[objs.Length];
            for (var i = 0; i < objs.Length; i++)
            {
                prefabObject[i] = objs[i] as T;
            }
        }

        if (prefabObject != null)
            return prefabObject;

        AssetBundle bundle = bundleList[bundleKey];
        if (bundle == null)
        {
            return null;
        }

        prefabObject = bundle.LoadAllAssets() as T[];
        return prefabObject;

#endif
    }


}
